package cn.yj.relay.common.token;

import cn.yj.relay.common.exception.Error;
import cn.yj.relay.common.utils.ServletUtils;
import cn.yj.relay.common.utils.StringUtils;
import cn.yj.relay.core.entity.Admin;
import cn.yj.relay.core.entity.Emp;
import cn.yj.relay.core.service.IAdminService;
import cn.yj.relay.core.service.IEmpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

import static cn.yj.relay.common.utils.FilterNull.isBlank;
import static cn.yj.relay.common.utils.FilterNull.isNull;

/**
 * <p>
 *
 * </p>
 *
 * @author 永健
 * @since 2019-05-31 14:22
 */
@Component
public class AppAuthTokenHandler extends DeFaultTokenHandler
{
    Logger logger = LoggerFactory.getLogger(AppAuthTokenHandler.class);

    private static final String APP_LOGIN_AUTH_TOKEN_NAME = "auth";

    @Autowired
    private IEmpService iEmpService;

    @Autowired
    private IAdminService iAdminService;

    private static Map<String, String> ROLE = new HashMap<>();

    public synchronized static void saveUserRole(String token, String role)
    {
        ROLE.put(token, role);
    }

    /**
     * <br>
     * 过期时间
     */
    private static final Integer EXPIRE_DAY = 1;


    /**
     * 创建token
     *
     * @param openId
     * @return 返回加密后的token
     */
    @Override
    public String doCreate(String openId)
    {
        Emp user = iEmpService.getByToken(openId);
        isNull(user, "请求凭证有误");
        return uuid();
    }


    public String getRequestToken()
    {
        String header = ServletUtils.getRequest().getHeader(APP_LOGIN_AUTH_TOKEN_NAME);
        if (StringUtils.isNull(header))
        {
            return null;
        }
        return header;
    }

    /**
     * <br>
     * 退出
     */
    @Override
    public void doDelete(String openId)
    {

    }

    public void checkLoginAuth()
    {
        String requestToken = getRequestToken();
        isBlank(requestToken, Error.请求凭证有误);
        getRole();
    }

    public Emp getEmp()
    {
        String requestToken = getRequestToken();
        Emp token = iEmpService.getByToken(requestToken);
        isNull(token, Error.请求凭证有误);
        return token;
    }

    public String getRole()
    {
        String s = ROLE.get(getRequestToken());
        isBlank(s, Error.请求凭证有误);
        return s;
    }

    public Admin getAdmin()
    {
        String requestToken = getRequestToken();
        Admin token = iAdminService.getUserByToken(requestToken);
        isNull(token, Error.请求凭证有误);
        return token;
    }


}
